/**
 * Created by li hong 2017/10/25 0025.
 */

var alterable = null;
var windModel = null;
var tableData = null;
var wind = null;
$(function () {
    var table = new tableFactory();
    addListeners(table);
    upload();
});

function tableFactory() {
    var me = this;
    me.windData = null;//风电场数据
    me.data = null;//风机数据
    me.maxId = 0;
    var init = function () {
        $.when(me.loadSelectData()).then(function () {
            $("#curve").bootstrapTable({
                method: 'get',					  //请求方式（*）
                striped: true,					  //是否显示行间隔色
                cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,				   //是否显示分页（*）
                sortable: true,					 //是否启用排序
                sortOrder: "desc",				   //排序方式
                sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,					   //初始化加载第一页，默认第一页
                search: true,					   //是否显示表格搜索，只能进行客户端搜索
                strictSearch: false,                //true为全匹配，false为模糊查询
                showColumns: true,				  //是否显示筛选列按钮
                showRefresh: true,			  //是否显示刷新按钮
                clickToSelect:true,				//是否启用点击选中行
                showToggle: false,					//是否显示详细视图和列表视图的切换按钮
                cardView: false,					//是否显示详细视图
                detailView: false,				   //是否显示父子表
                singleSelect: false,                //是否支持多选,false表示支持多选，true表示不支持
                //undefinedText: '_',              //当数据为undefined时显示的字符
                height: 'auto',
                pageSize: 10,
                pageList: [5,10,20],
                columns: [/*{
                 field: 'check',checkbox: true
                 }, */{
                    title:'序号',
                    field: 'check',
                    checkbox: true,
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '风机型号',
                    field: 'fanModel',
                    align: 'center',
                    valign: 'middle'
                },{
                    title: '标准空气密度',
                    field: 'density',
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '风速(m/s)',
                    field: 'speed',
                    align: 'center',
                    valign: 'middle',
                    sortable: true
                }, {
                    title: '功率(kw)',
                    field: 'power',
                    align: 'center',
                    valign: 'middle'
                }/* {
                 title: '日期',
                 field: 'createTime',
                 align: 'center',
                 valign: 'middle'
                 }*/]
            });
            // me.loadData();
        });
    }
    init();
}

tableFactory.prototype = {
    //加载标准功率曲线数据
    loadData: function () {
        var me = this;
        var index = layer.load(1);
        $.getJSON('../curveManage/selectAll', '', function (_data) {
            me.data = _data;
            $("#curve").bootstrapTable("load", _data);
            layer.close(index);
        })
    },

    save: function () {
        var me = this;
        var html = [];
        html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
        html.push('<tr><td>风机型号：</td><td><input type="text" class="form-control" id="new-fanModel" /></td></tr>');
        html.push('<tr><td>空气密度：</td><td><input type="text" class="form-control" id="new-density" /></td></tr>');
        html.push('<tr><td>风速(m/s)：</td><td><input type="text" class="form-control" id="new-speed" /></td></tr>');
        html.push('<tr><td>功率(mw)：</td><td><input type="text" class="form-control" id="new-power" /></td></tr>');
        html.push('</table></div>');

        layer.open({
            type: 1,
            area: '400px',
            title: '添加信息',
            btn: ['确定'],
            //shadeClose: true,//开启遮罩关闭
            content: html.join(''),
            yes: function (index) {
                var p = {
                    //departmentid: me.maxId + 1,
                    fanModel: $("#new-fanModel").val(),
                    density: $("#new-density").val(),
                    speed: $("#new-speed").val(),
                    power: $("#new-power").val(),
                };
                layer.close(index);
                $.ajax({
                    url : "../curveManage/insert",
                    type : "post",
                    contentType : "application/json",
                    dataType : "json",
                    data : JSON.stringify(p),//转换成字符串。后台使用了RequestBody注解
                    success : function(data) {
                        if (data === true) {
                            me.select();
                            //me.loadData();
                            layer.msg("添加成功！", {icon: 1});
                        } else {
                            layer.msg("添加失败！", {icon: 2});
                        }
                    },
                    error :function(){
                        layer.msg("添加失败！", {icon: 2});
                    }
                });
            }
        });
    },
    delete: function () {
        var me = this;
        var selects = $('#curve').bootstrapTable("getSelections");
        if (selects.length > 0) {
            layer.confirm('确定删除?', {icon: 3, title:'提示'}, function (index) {
                //do something
                var deletes = [];
                var id;
                $.each(selects, function (index, item) {
                    deletes.push({
                        id: item.id,
                    });
                    //id = item.id;
                });

                $.ajax({
                    url: '../curveManage/delete',
                    type: 'post',
                    contentType : 'application/json;charset=utf-8', //设置请求头信息
                    dataType: 'json',
                    data: /*{"id":id},*/JSON.stringify(deletes),
                    success: function (data) {
                        if (data > 0) {
                            //me.loadData();
                            me.select();
                            layer.msg("已删除"+data+"条数据！", {icon: 1});
                        }
                    }
                });
                layer.close(index);
            });
        } else {
            layer.msg("请选择要删除的信息！", {icon: 0});
        }
    },
    edit: function () {
        var me = this;
        var selects = $('#curve').bootstrapTable("getSelections");
        var len = selects.length;
        if (len === 1) {
            var editItem = selects[0];
            var html = [];
            html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
            html.push('<tr><td>风机型号：</td><td><input type="text" class="form-control" id="edit-fanModel" /></td></tr>');
            html.push('<tr><td>空气密度：</td><td><input type="text" class="form-control" id="edit-density" /></td></tr>');
            html.push('<tr><td>风速(m/s)：</td><td><input type="text" class="form-control" id="edit-speed" /></td></tr>');
            html.push('<tr><td>功率(kw)：</td><td><input type="text" class="form-control" id="edit-power" /></td></tr>');
            html.push('</table></div>');
            layer.open({
                type: 1, area: '500px', title: '修改功率曲线', btn: ['确定'],
                content: html.join(''),
                success: function () {
                    $('#edit-fanModel').val(editItem.fanModel);
                    $('#edit-density').val(editItem.density);
                    $('#edit-speed').val(editItem.speed);
                    $('#edit-power').val(editItem.power);
                },
                yes: function (index) {
                    var p = {
                        id:editItem.id,
                        fanModel: $("#edit-fanModel").val(),
                        density: $("#edit-density").val(),
                        speed: $("#edit-speed").val(),
                        power: $("#edit-power").val(),
                    };
                    layer.close(index);
                    $.ajax({
                        url : "../curveManage/update",
                        type : "POST",
                        contentType : "application/json",
                        dataType : "json",
                        data : JSON.stringify(p),//转换成字符串。后台使用了RequestBody注解
                        success : function(data) {
                            if (data === true) {
                                //me.loadData();
                                me.select();
                                layer.msg("修改成功！", {icon: 1});
                            } else {
                                layer.msg("修改失败！", {icon: 2});
                            }
                        },
                        error :function(){
                            alert("添加失败");
                        }
                    });
                }
            });
        } else if (len > 1){
            layer.msg("只能选择一条信息！", {icon: 0});
        } else if (len === 0) {
            layer.msg("请选择要修改的信息！", {icon: 0});
        }
    },
//加载下拉菜单的风电场的名称
    loadSelectData:function(){
        var me = this;
        var selectfan = $("#selectfan");
        $.getJSON('../curveManage/getSelectData', '', function (_data) {
            me.windModel = _data;
            $.each(_data, function (index, item) {
                selectfan.append("<option>"+item.fanModel+"</option>");
            });
            me.select();
        })
    },
    select:function () {
        var windSpeed = new Array();
        var power =new Array();
        var arr =new Array();
        var title =new Array();
        var me = this;
        var name = $("#selectfan").find("option:selected").text();
        var data = {"fanModel":name};
        /* $.post("/curveManage/getSelectOne", data, function (data) {

         })*/
        $.ajax({
            url : "../curveManage/getSelectOne",
            type : "post",
            contentType : "application/json",
            dataType : "json",
            data : JSON.stringify(data),//转换成字符串。后台使用了RequestBody注解
            success : function(data) {
                $.each(data, function (index, item) {
                    windSpeed.push(item.speed);
                    power.push(item.power);
                    arr.push(item.fanModel);
                });
                title.push(arr[0]);
                lodaTu(windSpeed,power,title);
                console.log(data);
                $("#curve").bootstrapTable("load", data);
            }
        })
    },
    export:function () {
        $.ajax({
            url: '../curveManage/CsvExport',
            type: 'get',
            contentType : 'application/json;charset=utf-8', //设置请求头信息
            dataType: 'json',
            data: "",/*JSON.stringify(deletes),*/
            success: function (data) {
                if (data === true) {
                    layer.msg("下载成功！", {icon: 1});
                }
            }
        });
    }
};

function addListeners (tableObj) {
    $('#btn-add').off('click');
    $('#btn-delete').off('click');
    $('#btn-edit').off('click');
    $("#selectfan").off('change');

    $('#btn-add').on('click', function () {
        tableObj.save();
    });
    $('#btn-delete').on('click', function () {
        tableObj.delete();
    });
    $('#btn-edit').on('click', function () {
        tableObj.edit();
    });

    $('#selectfan').on('change', function () {
        tableObj.select();
    });
    $('#btn-export').on('click', function () {
        tableObj.export();
    });
}
//导入
function upload(){
    layui.use('upload', function(){
        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#btn-upload', //绑定元素
            url: '../curveManage/CsvImport', //上传接口
            accept: 'file',//指定允许上传的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
            exts : 'csv',//指定文件的后缀
            done: function(res){
                if (res === true) {
                    layer.msg("上传成功！", {icon: 1});
                    //window.location.href="/curveManage/main";
                } else {
                    layer.msg("曲线已存在，或风机型号不存在！", {icon: 2});
                }
            }
            ,error: function(){
                //请求异常回调
            }
        });
    });
}



//加载曲线图
function lodaTu(speed,power,title) {
    var myChart = echarts.init(document.getElementById("main"));
//vapp.title = '多 X 轴示例';
    var colors = ['#d14a61', '#675bba','	#98FB98','#8B6914','#fff'];

    /*定义风速功率*/
    option = {
        color: colors,
        title:{
            text:'标准功率曲线',
            textStyle:{
                color:'#fff'
            },
            //subtext: '湖北新能源有限公司',
            x: 'center'
        },
        tooltip: {
            //trigger: 'axis',//显示表格状态信息
            axisPointer: {
                type: 'cross'
            }
        },
        ///右顶部工具栏
        toolbox: {
            show : true,
            feature : {
                /*mark : {show: true},
                dataView : {show: true, readOnly: false},
                magicType : {show: true, type: ['line', 'bar']},
                restore : {show: true},*/
                saveAsImage : {show: true}
            }
        },


        legend: {
            show:true,
            selectedMode: 'multiple',
            data:title,
            y:'15%',
            x:'center'
        },
        grid: {
            top: 70,
            bottom: 50
        },
        xAxis: [
            {
                //splitLine:{show: false},//去除网格线
                type: 'category',
                boundaryGap : false,//上边时间轴全部显示
                axisTick: {
                    alignWithLabel: true
                },
                axisLine: {
                    onZero: false,
                    lineStyle: {
                        //color: colors[2]
                    }
                },
                /* axisPointer: {
                 label: {
                 formatter: function (params) {
                 return '降水量  ' + params.value
                 + (params.seriesData.length ? '：' + params.seriesData[0].data : '');
                 }
                 }
                 },*/
                axisLabel:{
                    interval:0,
                    rotate:45,//倾斜度 -90 至 90 默认为0
                    margin:5,
                    textStyle:{
                        fontWeight:"bolder",
                        color:"#fff"
                    }
                },
                data: speed
            },
        ],
        yAxis: [
            {
                splitLine:{show: false},//去除网格线
                type: 'value',
                show: true,
                name: '功率(kw)',
                nameTextStyle:{
                    color:'#fff'
                },
                axisLabel:{
                    formatter: '{value}',
                    textStyle:{
                        fontWeight:"bolder",
                        color:"#fff"
                    }
                }
            },
        ],
        series: [
            {
                name:'G58',
                type:'line',
                xAxisIndex: 0,
                stack: '总量',
                smooth: true,//使线条更平滑
                //symbol:'none',  //这句就是去掉点的
                data: power,
                itemStyle:{
                    normal:{
                        lineStyle:{
                            width:2,
                            //type:'dotted'dashed  //'dotted'虚线 'solid'实线
                            color: '#fff',
                            type: 'solid',
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 0, 0, 0.5)',
                            smooth:true,
                            width:2
                        }
                    }
                }
            }
        ]
    };
    myChart.setOption(option);
}

